package com.xuequ.answerme.account;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.xuequ.answerme.main.MainActivity;
import com.xuequ.answerme.R;
import com.xuequ.answerme.beans.UserBean;
import com.xuequ.answerme.manager.UserManager;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobSMS;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.RequestSMSCodeListener;
import cn.bmob.v3.listener.VerifySMSCodeListener;

/**
 * Created by Shijie on 2015/10/1.
 */
public class LoginJoinActivity extends AppCompatActivity {

    private String BmobKey = "0694f1a1fccdf3450e9d7ad29f76f2eb";

    private TextView mLoginText;//登录文字按钮
    private TextView mJoinText;//注册文字按钮

    private TextView mBackText;//返回登录界面文字返回按钮1
    private TextView mNextText;//下一步注册文字按钮
    private TextView mGetText;//获取短信验证码

    private TextView mBackText2;//返回登陆界面文字返回按钮2
    private TextView mConfirmText;//注册完成按钮

    private UserBean newUser;//注册新用户
    private String phoneNumber;//注册需验证电话的号码
    private String SMSCode;//注册获得的短信验证码
    private String registerUsername;//注册用户名
    private String registerPassword;//注册密码
    private String loginAccount;//登录帐号（手机、邮箱或用户名）
    private String loginPassword;//登录密码

    private TextInputLayout mLoginAccountLayout;
    private TextInputLayout mLoginPasswordLayout;
    private TextInputLayout mRegisterPhoneNumberLayout;
    private TextInputLayout mGetSMSCodeLayout;
    private TextInputLayout mRegisterUsernameLayout;
    private TextInputLayout mRegisterPasswordLayout;

    private RelativeLayout mRegisterLayout;//注册界面布局1
    private RelativeLayout mRegisterLayout2;//注册见面布局2
    private RelativeLayout mLoginLayout;//登录界面布局

    private UserManager userManager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        Bmob.initialize(this, BmobKey);

        if (BmobUser.getCurrentUser(LoginJoinActivity.this) != null) {
            startActivity(new Intent(LoginJoinActivity.this, MainActivity.class));
            finish();
        }

        initViews();
    }

    /**
     * 初始化控件
     */
    private void initViews() {
        mLoginAccountLayout = (TextInputLayout) findViewById(R.id.login_account_textInputLayout);
        mLoginPasswordLayout = (TextInputLayout) findViewById(R.id.login_password_textInputLayout);
        mRegisterPhoneNumberLayout = (TextInputLayout) findViewById(R.id.register_phoneNumber_textInputLayout);
        mGetSMSCodeLayout = (TextInputLayout) findViewById(R.id.register_SMSCode_textInputLayout);
        mRegisterUsernameLayout = (TextInputLayout) findViewById(R.id.register_username_textInputLayout);
        mRegisterPasswordLayout = (TextInputLayout) findViewById(R.id.register_password_textInputLayout);

        mLoginLayout = (RelativeLayout) findViewById(R.id.login_relativeLayout);
        mRegisterLayout = (RelativeLayout) findViewById(R.id.register_relativeLayout);
        mRegisterLayout2 = (RelativeLayout) findViewById(R.id.register2_relativeLayout);

        //先把注册界面1、2向下移到300的位置（0->300）
        ObjectAnimator.ofFloat(mRegisterLayout, "translationY", 300f).setDuration(100).start();
        ObjectAnimator.ofFloat(mRegisterLayout2, "translationY", 300f).setDuration(100).start();

        mLoginText = (TextView) findViewById(R.id.login_textView);
        mJoinText = (TextView) findViewById(R.id.register_textView);
        mBackText = (TextView) findViewById(R.id.back_textView);
        mGetText = (TextView) findViewById(R.id.get_SMSCode_textView);
        mNextText = (TextView) findViewById(R.id.next_textView);
        mBackText2 = (TextView) findViewById(R.id.back2_textView);
        mConfirmText = (TextView) findViewById(R.id.confirm_textView);


        //______________________________________________________________________________________________________________
        //所有TextView的点击事件

        //点击手机登陆
        mLoginText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                Log.i("LoginJoinLActivity", "click Login");

                loginAccount = mLoginAccountLayout.getEditText().getText().toString();
                loginPassword = mLoginPasswordLayout.getEditText().getText().toString();
                //网络连接
                if (loginAccount != null && loginPassword != null) {
                    doLogin(v);
                }
            }
        });

        //点击跳转注册界面注册
        mJoinText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("LoginJoinLActivity", "click Join");
                //设置mLoginLayout转向mRegisterLayout的动画
                PropertyValuesHolder pvh1 = PropertyValuesHolder.ofFloat("translationY", 300f);//向下移到300的位置（0->300）
                PropertyValuesHolder pvh2 = PropertyValuesHolder.ofFloat("alpha", 0);//设置透明
                ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(mLoginLayout, pvh1, pvh2).setDuration(200);
                //监听动画前后来设置Visibility
                animator.addListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animation) {
                    }

                    @Override
                    public void onAnimationEnd(Animator animation) {
                        mLoginLayout.setVisibility(View.GONE);

                        PropertyValuesHolder pvh1 = PropertyValuesHolder.ofFloat("translationY", 0f);//向上移到0的位置（300->0）
                        PropertyValuesHolder pvh2 = PropertyValuesHolder.ofFloat("alpha", 1);//设置不透明
                        ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(mRegisterLayout, pvh1, pvh2).setDuration(200);
                        animator.addListener(new Animator.AnimatorListener() {
                            @Override
                            public void onAnimationStart(Animator animation) {
                                mRegisterLayout.setVisibility(View.VISIBLE);
                            }

                            @Override
                            public void onAnimationEnd(Animator animation) {
                                mLoginAccountLayout.getEditText().setText(null);
                                mLoginPasswordLayout.getEditText().setText(null);
                            }

                            @Override
                            public void onAnimationCancel(Animator animation) {

                            }

                            @Override
                            public void onAnimationRepeat(Animator animation) {

                            }
                        });
                        animator.start();
                    }

                    @Override
                    public void onAnimationCancel(Animator animation) {

                    }

                    @Override
                    public void onAnimationRepeat(Animator animation) {

                    }
                });
                animator.start();
            }
        });

        //返回到LOGIN界面
        mBackText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("LoginJoinLActivity", "click Back");
                //设置mRegisterLayout转向mLoginLayout的动画
                PropertyValuesHolder pvh1 = PropertyValuesHolder.ofFloat("translationY", 300f);//向下移到300的位置（0->300）
                PropertyValuesHolder pvh2 = PropertyValuesHolder.ofFloat("alpha", 0);//设置透明
                ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(mRegisterLayout, pvh1, pvh2).setDuration(200);
                //监听动画前后来设置Visibility
                animator.addListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animator animation) {
                        mRegisterLayout.setVisibility(View.GONE);

                        PropertyValuesHolder pvh1 = PropertyValuesHolder.ofFloat("translationY", 0f);//向上移到0的位置（300->0）
                        PropertyValuesHolder pvh2 = PropertyValuesHolder.ofFloat("alpha", 1);//设置不透明
                        ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(mLoginLayout, pvh1, pvh2).setDuration(200);
                        animator.addListener(new Animator.AnimatorListener() {
                            @Override
                            public void onAnimationStart(Animator animation) {
                                mLoginLayout.setVisibility(View.VISIBLE);
                            }

                            @Override
                            public void onAnimationEnd(Animator animation) {
                                mRegisterPhoneNumberLayout.getEditText().setText(null);
                                mGetSMSCodeLayout.getEditText().setText(null);
                            }

                            @Override
                            public void onAnimationCancel(Animator animation) {

                            }

                            @Override
                            public void onAnimationRepeat(Animator animation) {

                            }
                        });
                        animator.start();
                    }

                    @Override
                    public void onAnimationCancel(Animator animation) {

                    }

                    @Override
                    public void onAnimationRepeat(Animator animation) {

                    }
                });
                animator.start();
            }
        });

        //点击接受短信验证码
        mGetText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                phoneNumber = mRegisterPhoneNumberLayout.getEditText().getText().toString();
                if (userManager == null) {
                    userManager = new UserManager();
                }
                userManager.FindPhoneNumberIsValid(LoginJoinActivity.this, phoneNumber, new UserManager.FindPhoneNumberIsValidListener() {
                    @Override
                    public void findPhoneNumberIsValidOnSuccess(Integer isValid) {
                        Log.i("isValid", "" + isValid);
                        if (isValid == 0) {
                            BmobSMS.requestSMSCode(LoginJoinActivity.this, phoneNumber, "Test", new RequestSMSCodeListener() {
                                @Override
                                public void done(Integer integer, BmobException e) {
                                    Log.i("Exception", "" + e);
                                    //如果下面判断不加 e!=null，当号码可注册时就会报错
                                    if (e != null && (e.toString().contains("Invlid Mobile Phone Number")
                                            || e.toString().contains("phoneNumber can't be empty")
                                            || e.toString().contains("mobilePhoneNumber Must be valid mobile number"))) {
                                        Snackbar.make(v, "请正确输入手机号码", Snackbar.LENGTH_LONG).setAction("Action", null).show();
                                    }
                                }
                            });
                        } else {
                            Snackbar.make(v, "手机号已被注册", Snackbar.LENGTH_LONG).setAction("Action", null).show();
                        }
                    }

                    @Override
                    public void findPhoneNumberIsValidOnFailure(String FailureMSG) {

                    }
                });
            }
        });

        //点击进行验证码验证，若成功则跳转下一界面操作
        mNextText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SMSCode = mGetSMSCodeLayout.getEditText().getText().toString();

                if (SMSCode != null) {
                    BmobSMS.verifySmsCode(LoginJoinActivity.this, phoneNumber, SMSCode, new VerifySMSCodeListener() {
                        @Override
                        public void done(BmobException e) {
                            if (e == null) {
                                registerNewUser();
                            } else {
                                Log.i("verify", "failure");
                            }
                        }
                    });
                }
            }
        });

        //返回到LOGIN界面
        mBackText2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PropertyValuesHolder pvh1 = PropertyValuesHolder.ofFloat("translationY", 300f);//向下移到300的位置（0->300）
                PropertyValuesHolder pvh2 = PropertyValuesHolder.ofFloat("alpha", 0);//设置透明
                ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(mRegisterLayout2, pvh1, pvh2).setDuration(200);
                //监听动画前后来设置Visibility
                animator.addListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animation) {
                    }

                    @Override
                    public void onAnimationEnd(Animator animation) {
                        mRegisterLayout2.setVisibility(View.GONE);

                        PropertyValuesHolder pvh1 = PropertyValuesHolder.ofFloat("translationY", 0f);//向上移到0的位置（300->0）
                        PropertyValuesHolder pvh2 = PropertyValuesHolder.ofFloat("alpha", 1);//设置不透明
                        ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(mLoginLayout, pvh1, pvh2).setDuration(200);
                        animator.addListener(new Animator.AnimatorListener() {
                            @Override
                            public void onAnimationStart(Animator animation) {
                                mLoginLayout.setVisibility(View.VISIBLE);
                            }

                            @Override
                            public void onAnimationEnd(Animator animation) {
                                mRegisterUsernameLayout.getEditText().setText(null);
                                mRegisterPasswordLayout.getEditText().setText(null);
                            }

                            @Override
                            public void onAnimationCancel(Animator animation) {

                            }

                            @Override
                            public void onAnimationRepeat(Animator animation) {

                            }
                        });
                        animator.start();
                    }

                    @Override
                    public void onAnimationCancel(Animator animation) {

                    }

                    @Override
                    public void onAnimationRepeat(Animator animation) {

                    }
                });
                animator.start();
            }
        });

        //确定注册完毕
        mConfirmText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                registerUsername = mRegisterUsernameLayout.getEditText().getText().toString();
                registerPassword = mRegisterPasswordLayout.getEditText().getText().toString();
                if (registerUsername != null && registerPassword != null) {
                    newUser.setUsername(registerUsername);
                    newUser.setPassword(registerPassword);
                    if (userManager == null) {
                        userManager = new UserManager();
                    }
                    userManager.AddNewUser(LoginJoinActivity.this, newUser, new UserManager.AddNewUserListener() {
                        @Override
                        public void addNewUserOnSuccess() {
                            Log.i("register", "success");
                            Log.i("currentUser", " " + BmobUser.getCurrentUser(LoginJoinActivity.this, UserBean.class).getUsername());
                            //跳到主页
                            startActivity(new Intent(LoginJoinActivity.this, MainActivity.class));
                            finish();
                        }

                        @Override
                        public void addNewUserOnFailure(String FailureMSG) {
                            Log.i("register", "failure" + FailureMSG);
                            if (FailureMSG.contains("username '") && FailureMSG.contains("' already taken.")) {
                                Log.i("register", "用户名重复");
                            }
                        }
                    });
                }
                Log.i("newUser", "go");
            }
        });

        //所有TextView点击事件结束
        //___________________________________________________________________________________________________________

    }

    /**
     * 做手机登录操作
     */
    private void doLogin(final View v) {

        if (userManager == null) {
            userManager = new UserManager();
        }

        Log.i("login", "手机登录");
        userManager.LoginByPhoneNumber(LoginJoinActivity.this, loginAccount, loginPassword, new UserManager.LoginListener() {
            @Override
            public void loginOnSuccess(UserBean userBean) {
                Log.i("currentUser", " " + BmobUser.getCurrentUser(LoginJoinActivity.this, UserBean.class).getUsername());
                //跳到主页
                startActivity(new Intent(LoginJoinActivity.this, MainActivity.class));
                finish();
            }

            @Override
            public void loginOnFailure(String FailureMSG) {
                Snackbar.make(v, FailureMSG, Snackbar.LENGTH_LONG).setAction("Action", null).show();
            }
        });
    }

    /**
     * 验证成功后我们建立一个新用户
     */
    private void registerNewUser() {
        nextStepToRegister();
        newUser = new UserBean();
        newUser.setMobilePhoneNumber(phoneNumber);
        newUser.setMobilePhoneNumberVerified(true);
    }

    /**
     * 跳到注册的第二个页面
     */
    private void nextStepToRegister() {
        PropertyValuesHolder pvh1 = PropertyValuesHolder.ofFloat("translationY", 300f);//向下移到300的位置（0->300）
        PropertyValuesHolder pvh2 = PropertyValuesHolder.ofFloat("alpha", 0);//设置透明
        ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(mRegisterLayout, pvh1, pvh2).setDuration(200);
        //监听动画前后来设置Visibility
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                mRegisterLayout.setVisibility(View.GONE);

                PropertyValuesHolder pvh1 = PropertyValuesHolder.ofFloat("translationY", 0f);//向上移到0的位置（300->0）
                PropertyValuesHolder pvh2 = PropertyValuesHolder.ofFloat("alpha", 1);//设置不透明
                ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(mRegisterLayout2, pvh1, pvh2).setDuration(200);
                animator.addListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animation) {
                        mRegisterLayout2.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onAnimationEnd(Animator animation) {
                        mRegisterPhoneNumberLayout.getEditText().setText(null);
                        mGetSMSCodeLayout.getEditText().setText(null);
                    }

                    @Override
                    public void onAnimationCancel(Animator animation) {

                    }

                    @Override
                    public void onAnimationRepeat(Animator animation) {

                    }
                });
                animator.start();
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        animator.start();
    }


    /**
     * 监听系统的back键
     */

}
